// pages/shop/create_order/create_order.js
var api = require('../../../api/api');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: '',
    shopLists: [],
    carType: 0, //0 购物车  1 立即购买
    totalPrice: 0,
    totalNum: 0,
    method: ['快递配送', '到店自提'],
    methodIndex: 0, //收货方式:0=快递配送,1=到店自提
    payType:['余额支付','微信支付'],
    courier_fee:0,
    pay_way: 0 //0=余额支付,1=微信支付  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.type == "buyNow") {
      this.setData({
        carType: 1
      })
    }
    let carType = this.data.carType;
    let shopLists = [];
    if (carType == 1) { //立即购买
      console.log('1111')
      shopLists = wx.getStorageSync('buyNowCars')
    } else {
      shopLists = wx.getStorageSync('cars')
    }

    this.setData({
      shopLists
    })
    this.courierFee();
   
  },
   courierFee(){
     api.get('/goods/courier_fee').then(res=>{
        this.setData({
          courier_fee:res.price
        })
        this.checkTotalPrice();
     })
   },
  chnagePayWay(e){
    let index = e.currentTarget.dataset.index;
    this.setData({
      pay_way:index
    })
  },
  changeMethod(e) {
    let index = e.currentTarget.dataset.index;
    let address = '';
    if (index == 1) {
      address = wx.getStorageSync('shStore')
    } else {
      address = wx.getStorageSync('address')
    }
    this.setData({
      methodIndex: index,
      address
    })
    this.checkTotalPrice();
  },

  stepperChange(e) {
    //e.detail.value 改变后的值
    //e.detail.type 操作的类型（输入，增加按钮，减少按钮）
    //e.detail.index 当前组件的索引
    //根据项目逻辑 自行处理
    let index = e.detail.index;
    let shopLists = this.data.shopLists;
    shopLists[index].num = e.detail.value;
    this.setData({
      shopLists
    })
    this.checkTotalPrice()
  },
  //地址列表
  address_list() {
    if (this.data.methodIndex == 0) { //快递配送
      wx.navigateTo({
        url: '/pages/addressList/addressList',
      })
      // wx.chooseAddress({
      //   success(res) {
      //     wx.setStorageSync('address', res)
      //   },
      //   fail(err) {
      //     console.log(err)
      //   }
      // })
    } else { //到店
      wx.navigateTo({
        url: '/pages/store_list/store_list'
      })
    }
  },
  checkTotalPrice() { //统计金额，数量
    let totalPrice = 0;
    let totalNum = 0;
    let shopLists = this.data.shopLists;
    if(!this.data.methodIndex){ //到店自提
      totalPrice = totalPrice + this.data.courier_fee;
    }
    shopLists.map(item => {
      if(item.selected){
        totalPrice = item.price * item.num + totalPrice;
        totalNum = item.num + totalNum;
      }
    
    })
    this.setData({
      totalPrice,
      totalNum
    })
  },
  createOrder() {
    if(!this.data.address){
      wx.showToast({
        title: '请选择收货地址',
        icon:'none'
      })
      return false;
    }
    let cars = [];
    let shopLists = this.data.shopLists;
    shopLists.map(item => {
      cars.push({
        good_id: item.id,
        good_number: item.num
      });
    })
    let address = {}

    if (this.data.methodIndex == 1) {
      address.shop_id = this.data.address.id;
      address.area = '';
      address.address = '';
      address.name = '';
      address.phone = '';
    } else {
      address.shop_id = 0;
      address.area = this.data.address.area;
      address.address = this.data.address.address;
      address.name = this.data.address.name;
      address.phone = this.data.address.phone;
    }

    api.post('/goods/pay', {
      pay_way: this.data.pay_way,
      method: this.data.methodIndex,
      cars: cars,
      address: address,
    }).then(res => {
        if(this.data.carType == 0){ //购物车
           let oldCars = wx.getStorageSync('cars');
           let newCars = [];
            oldCars.map(sitem=>{
                if(!sitem.selected){
                  newCars.push(sitem)
                }
              })
           wx.setStorageSync('cars', newCars);
        }
        if(this.data.pay_way == 0){
          wx.showToast({
            title: '支付成功',
            icon: 'none',
            success: function () {
              setTimeout(() => {
                wx.navigateTo({
                  url: '/pages/shop_order/order_lists/order_lists',
                })
              }, 1000)
            }
          })
        }else{
          wx.requestPayment({
            ...res.payInfo,
            success: function (res) {
              console.log('success:' + JSON.stringify(res));
              wx.showToast({
                title: '支付成功',
                icon: 'none',
                success: function () {
                  setTimeout(() => {
                    wx.navigateTo({
                      url: '/pages/shop_order/order_lists/order_lists',
                    })
                  }, 1000)
                }
              })
            },
            fail: function (err) {
              console.log('fail:' + JSON.stringify(err));
              if (err.errMsg == "requestPayment:fail cancel") {
                wx.showToast({
                  title: '取消支付',
                  icon: 'none',
                  duration: 3000
                })
              } else {
                wx.showToast({
                  title: JSON.stringify(err),
                  icon: 'none',
                  duration: 3000
                })
              }
            }
          });
    
        }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let address = '';
    if (this.data.methodIndex == 0) { //快递
      address = wx.getStorageSync('address');
    } else { //门店
      address = wx.getStorageSync('shStore');
    }

    if (address) {
      this.setData({
        address
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})